﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GeoSyndication.Common
{
    public class Point
    {
        #region Private Fields

        private readonly double longitude;
        private readonly double latitude;
        private readonly double altitude;
        private string format = "{0} {1}";      // Default Setting, lat, lng 

        #endregion

        #region Public Properties

        public double Longitude
        {
            get { return longitude; }
        }

        public double Latitude
        {
            get { return latitude; }
        }

        public double Altitude
        {
            get { return altitude; }
        }

        public string Format
        {
            get
            {
                return format.Replace("{0}", "{lat}").Replace("{1}", "{lng}").Replace("{2}", "{alt}");
            }

            set
            {
                this.format = value.Replace("{lat}", "{0}").Replace("{lng}", "{1}").Replace("{alt}", "{2}");
            }
        } 

        #endregion

        #region Constructor

        public Point(double latitude, double longitude)
        {
            this.latitude = latitude;
            this.longitude = longitude;
        }

        public Point(double latitude, double longitude, double altitude)
        {
            this.latitude = latitude;
            this.longitude = longitude;
            this.altitude = altitude;
        } 

        #endregion

        #region Public Methods

        public override string ToString()
        {
            string retVal = string.Empty;

            retVal = string.Format(format, latitude.ToString(), longitude.ToString(), altitude.ToString());

            return retVal;
        }

        public static Point[] ParsePoints(string line)
        {
            List<Point> _line = new List<Point>();
            string[] s = line.Split(' ');

            if (s.Length % 2 != 0)
            {
                throw new ArgumentException("There must be an even number of points in a line or polygon");
            }

            for (int x = 0; x < s.Length + 1 / 2; x += 2)
            {
                Point p = new Point(double.Parse(s[x]), double.Parse(s[x + 1]));
                _line.Add(p);
            }

            return _line.ToArray();
        }

        public static Point[] ParsePoints(string line, string format)
        {
            List<Point> _line = new List<Point>();
            string[] s = line.Split(' ');

            for (int x = 0; x < s.Length + 1 / 2; x += 2)
            {
                Point p = new Point(double.Parse(s[x]), double.Parse(s[x + 1]));
                p.Format = format;
                _line.Add(p);
            }

            return _line.ToArray();
        } 

        #endregion
    }
}
